<template>
  <div class="default-main">
    <el-row class="panel-box"
            :gutter="20">
      <el-col :sm="12"
              :lg="6"
              class="panel">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>今日面板销售额$</span>
            </div>
          </template>
          <div class="card-content">
            <!-- <el-descriptions direction="vertical"
                             :column="2"
                             border>
              <el-descriptions-item label="今日销售额$"
                                    class-name="items">{{ todaySales.total_amount }}</el-descriptions-item>
              <el-descriptions-item label="昨日销售额$"
                                    class-name="items">{{ yesterdaySales.total_amount }}</el-descriptions-item>
              <el-descriptions-item label="今日运费折扣"
                                    class-name="items">{{ todaySales.shipping_fee_platform_discount }}</el-descriptions-item>
              <el-descriptions-item label="昨日运费折扣"
                                    class-name="items">{{ yesterdaySales.shipping_fee_platform_discount }}</el-descriptions-item>
              <el-descriptions-item label="今日平台折扣"
                                    class-name="items">{{ todaySales.platform_discount }}</el-descriptions-item>
              <el-descriptions-item label="昨日平台折扣"
                                    class-name="items">{{ yesterdaySales.platform_discount }}</el-descriptions-item>
            </el-descriptions> -->
            <h2>{{ todaySales.total_amount || 0 }}</h2>
            <el-row>
                <span class="mr">运费折扣:${{ todaySales.shipping_fee_platform_discount || 0 }}</span><br/>
                <span>平台折扣:${{ todaySales.platform_discount || 0 }}</span>
            </el-row>
          </div>
          <template #footer>
            <div class="card-footer">
              <span>昨日面板销售额:${{ yesterdaySales.total_amount || 0 }}</span>
            </div>
          </template>
        </el-card>
      </el-col>
      <el-col :sm="12"
              :lg="6"
              class="panel">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>今日订单量</span>
            </div>
          </template>
          <div class="card-content">
            <!-- <el-descriptions direction="vertical"
                             :column="2"
                             border>
              <el-descriptions-item label="今日订单量"
                                    class-name="items">{{ todaySales.count }}</el-descriptions-item>
              <el-descriptions-item label="昨日订单量"
                                    class-name="items">{{ yesterdaySales.count }}</el-descriptions-item>
            </el-descriptions> -->
            <h2>{{ todaySales.count || 0 }}</h2>
          </div>
          <template #footer>
            <div class="card-footer">
              <span>昨日订单量:{{ yesterdaySales.count || 0 }}</span>
            </div>
          </template>
        </el-card>
      </el-col>
      <el-col :sm="12"
              :lg="6"
              class="panel">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>广告消耗$</span>
            </div>
          </template>
          <div class="card-content">
            <!-- <el-descriptions direction="vertical"
                             :column="2"
                             border>
              <el-descriptions-item label="今日广告消耗"
                                    class-name="items">{{ advertisementData.spend }}</el-descriptions-item>
              <el-descriptions-item label="昨日广告消耗"
                                    class-name="items">{{ yesterdayAdvertisementData.spend }}</el-descriptions-item>
              <el-descriptions-item label="今日收入(商店)"
                                    class-name="items">{{ advertisementData.total_onsite_shopping_value }}</el-descriptions-item>
              <el-descriptions-item label="昨日收入(商店)"
                                    class-name="items">{{ yesterdayAdvertisementData.total_onsite_shopping_value }}</el-descriptions-item>
              <el-descriptions-item label="今日ROAS(商店)"
                                    class-name="items">{{ advertisementData.onsite_shopping_roas }}</el-descriptions-item>
              <el-descriptions-item label="昨日ROAS(商店)"
                                    class-name="items">{{ yesterdayAdvertisementData.onsite_shopping_roas }}</el-descriptions-item>
            </el-descriptions> -->
            <h2>{{ advertisementData.spend || 0 }}</h2>
          </div>
          <template #footer>
            <div class="card-footer">
              <span>昨日广告消耗:${{ yesterdayAdvertisementData.spend || 0 }}</span>
            </div>
          </template>
        </el-card>
      </el-col>
      <el-col :sm="12"
              :lg="6"
              class="panel">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>退款$</span>
            </div>
          </template>
          <div class="card-content">
            <!-- <el-descriptions direction="vertical"
                             :column="2"
                             border>
              <el-descriptions-item label="今日退款"
                                    class-name="items">0</el-descriptions-item>
              <el-descriptions-item label="昨日退款"
                                    class-name="items">0</el-descriptions-item>
            </el-descriptions> -->
            <h2>{{ refundSubtotal }}</h2>
          </div>
          <template #footer>
            <div class="card-footer">
              <span>昨日退款:${{ yesterdayRefundSubtotal }}</span>
            </div>
          </template>
        </el-card>
      </el-col>
    </el-row>
    <el-card class="chart-box">
      <template #header>
        <span class="chart-title">筛选</span>
        <el-radio-group v-model="day_change"
                        @change="dayChanges">
          <el-radio-button value="1">昨天</el-radio-button>
          <el-radio-button value="2">今天</el-radio-button>
          <el-radio-button value="3">本月</el-radio-button>
        </el-radio-group>
      </template>
      <div class="chart-content">
        <el-row class="operationsChartBlock">
          <div :ref="chartRefs.set"
               class="operationsChart"></div>
        </el-row>
        <el-row class="shopChartBlock">
          <div :ref="chartRefs.set"
               class="shopChart"></div>
        </el-row>
        <el-row class="adChartBlock">
          <div :ref="chartRefs.set"
               class="adChart"></div>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { useConfig } from '/@/stores/config'
import { reactive, ref, nextTick, onMounted, onActivated, onBeforeMount, watch, shallowRef } from 'vue'
import { useTemplateRefsList, useEventListener } from '@vueuse/core'
import * as echarts from 'echarts'
import { dashboard } from '/@/api/backend/dashboard'

const chartRefs = useTemplateRefsList<HTMLDivElement>()
const config = useConfig()
const day_change = ref('2')
const dayChanges = (v:any) => {
    getData(v)
}
const state: {
    charts: any[]
} = reactive({
    charts: []
})
const todaySales = ref({} as anyObj)
const yesterdaySales = ref({} as anyObj)
const advertisementData = ref({} as anyObj)
const yesterdayAdvertisementData = ref({} as anyObj)
const refundSubtotal = ref('')
const yesterdayRefundSubtotal = ref('')
const adDatas = ref([
    [],[],[]
] as any[])
const shopDatas = ref([
    [],[],[]
] as any[])
const saleDatas = ref([
    [],[],[]
] as any[])
const adChart = shallowRef({} as anyObj)
const shopChart = shallowRef({} as anyObj)
const operationsChart = shallowRef({} as anyObj)
const initAdChart = (init:Boolean = false) => {
    if(init) adChart.value = echarts.init(chartRefs.value[2] as HTMLElement)
    const option = {
        title: {
            text: '广告前十排名'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {},
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        dataset: {
            source: {
                '店铺': adDatas.value[0],
                '广告花费': adDatas.value[1],
                '广告收入': adDatas.value[2]
            }
        },
        xAxis: {
            type: 'value',
            boundaryGap: [0, 0.01]
        },
        yAxis: {
            type: 'category'
        },
        series: [
            {
                type: 'bar',
                itemStyle: {
                    color: '#409EFF'
                }
            },
            {
                type: 'bar',
                itemStyle: {
                    color: '#E6A23C'
                }
            }
        ]
    }
    adChart.value.setOption(option)
    init && state.charts.push(adChart.value)
} 

const initShopChart = (init:Boolean = false) => {
    if(init) shopChart.value = echarts.init(chartRefs.value[1] as HTMLElement)
    const option = {
        title: {
            text: '运营业绩'
        },
        legend: {},
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        dataset: {
            source: {
                '运营':  shopDatas.value[0],
                '运营花费':  shopDatas.value[1],
                '运营收入':  shopDatas.value[2],
            }
        },
        xAxis: { 
            type: 'category',
            axisTick: {
                interval: 0
            },
            axisLabel: {
                interval: 0
            }
        },
        yAxis: { 
            type: 'value'
        },
        series: [
            {
                type: 'bar',
                itemStyle: {
                    color: '#409EFF'
                }
            },
            {
                type: 'bar',
                itemStyle: {
                    color: '#E6A23C'
                }
            }
        ]
    }
    shopChart.value.setOption(option)
    init && state.charts.push(shopChart.value)
}

const initOperationsChart = (init:Boolean = false) => {
    if(init) operationsChart.value = echarts.init(chartRefs.value[0] as HTMLElement)
    const option = {
        title: {
            text: '销售统计'
        },
        legend: {},
        xAxis: {
            type: 'category'
        },
        yAxis: [
            {
                type: 'value',
                name: '总销售额',
                alignTicks: true
            },
            {
                type: 'value',
                name: '总订单量',
                alignTicks: true,
                splitLine: {
                    show: false
                }
            }
        ],
        dataset: {
            source: {
                '店铺': saleDatas.value[0],
                '总销售额': saleDatas.value[1],
                '总订单量': saleDatas.value[2],
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'line'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        series: [
            {
                type: 'bar',
                smooth: true,
                itemStyle: {
                    color: '#409EFF'
                }
            },
            {
                type: 'line',
                smooth: true,
                yAxisIndex: 1,
                itemStyle: {
                    color: '#E6A23C'
                }
            }
        ]
    }
    operationsChart.value.setOption(option)
    init && state.charts.push(operationsChart.value)
}

const echartsResize = () => {
    nextTick(() => {
        for (const key in state.charts) {
            state.charts[key].resize()
        }
    })
}

const getData = (day_change:any, init:Boolean = false) => {
    adDatas.value = [[],[],[]]
    shopDatas.value = [[],[],[]]
    saleDatas.value = [[],[],[]]
    return dashboard({ day_change }).then(res => {
        if(res.data) {
            const { 
                TodaysSalesRevenue, 
                YesterdaysSalesRevenue, 
                Advertisement, 
                YesterdayAdvertisement,
                StatisticalAdvertising,
                StatisticalSalesRevenue,
                StatisticsOfOperationalSalesRevenue,
                refund_subtotal,
                Yesterday_refund_subtotal
            } = res.data
            todaySales.value = TodaysSalesRevenue
            yesterdaySales.value = YesterdaysSalesRevenue
            advertisementData.value = Advertisement
            yesterdayAdvertisementData.value = YesterdayAdvertisement
            refundSubtotal.value = refund_subtotal
            yesterdayRefundSubtotal.value = Yesterday_refund_subtotal
            StatisticalAdvertising.forEach((v:any) => {
                adDatas.value[0].push(v.key || '')
                adDatas.value[1].push(v.value)
                adDatas.value[2].push(v.income)
            })
            StatisticsOfOperationalSalesRevenue.forEach((v:any) => {
                shopDatas.value[0].push(v.key || '')
                shopDatas.value[1].push(v.value)
                shopDatas.value[2].push(v.income)
            })
            StatisticalSalesRevenue.forEach((v:any) => {
                saleDatas.value[0].push(v.key || '')
                saleDatas.value[1].push(v.value)
                saleDatas.value[2].push(v.count)
            })
        }
        if(!init) {
            initAdChart()
            initShopChart()
            initOperationsChart()
        }
    })
}

onBeforeMount(() => {
    for (const key in state.charts) {
        state.charts[key].dispose()
    }
})

onActivated(() => {
    echartsResize()
})

onMounted(async () => {
    await getData(day_change.value, true)
    initAdChart(true)
    initShopChart(true)
    initOperationsChart(true)
    useEventListener(window, 'resize', echartsResize)
})

watch(
    () => config.layout.menuCollapse,
    () => {
        const timer = setTimeout(() => {
            echartsResize()
            clearTimeout(timer)
        }, .3 * 1000)
    }
)

</script>

<style scoped lang="scss">
//:deep(.el-card__body){
//    padding: 10px !important;
//}
:deep(.el-descriptions__body .el-descriptions__table.is-bordered .el-descriptions__cell){
    padding: 3px;
}
:deep(.items){
    word-break: break-all;   
}
.panel-box{
    :deep(.el-card__body){
        padding: 10px 20px;
    }
    .panel{
        margin-bottom: 10px;
    }
    .card-header{
        font-size: 20px;
    }
    .card-content{
        height: 90px;
        color: #303133;
        h2{
            font-size: 30px;
        }
        .el-row{
            margin: 12px 0;
        }
    }
    .mr{
        margin-right: 10px;
    }
}
.chart-box{
    .el-row + .el-row{
        margin-top: 20px;
    }
    :deep(.el-card__header){
        font-size: 16px;
        overflow: hidden;
        padding: 12px 20px;
    }
    .chart-title{
        vertical-align: -webkit-baseline-middle;
        cursor: default
    }
    :deep(.el-radio-group){
        float: right;
    }
    .adChartBlock{
        .adChart{
            width: 100%;
            height: 500px;
        }
    }
    .shopChartBlock{
        .shopChart{
            width: 100%;
            height: 400px;
        }
    }
    .operationsChartBlock{
        .operationsChart{
            width: 100%;
            height: 400px;
        }
    }
}
</style>